package wx.actions;

import com.google.gson.Gson;
import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.DateUtils;
import com.jinyou.utils.common.ValidateUtil;
import com.jinyou.utils.common.jyassert.JYAssertUtils;
import map.HttpRequest;
import net.sf.json.JSONObject;
import o2o.business.sms.JYSmsSeverBusiness;
import o2o.business.sms.data.SMS_TYPE;
import o2o.cache.sys.SysConfigPayMemory;
import o2o.cache.sys.SysConfigXcxPushMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.dao.PO.sys.SysConfigXcxPush;
import o2o.dao.PO.common.IsBindAccount;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.device.door.DeviceCompanyContact;
import o2o.dao.PO.sys.SysConfigPay;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.user.UserInfoVO;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.system.data.SYS_SETTINGS;
import o2o.web.actions.user.UserLogin;
import o2o.web.actions.user.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import pay.config.WeixinConfig;
import wx.dao.AccessToken;
import wx.dao.WXMsgTemplate;
import wx.utils.WeixinUtil;
import wx.utils.gzh.MessageUtil;
import wx.utils.gzh.WXTokenCheckoutUtil;
import wx.utils.gzh.WXXcxMan;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

//微信公众号相关的
@Controller
public class WXGZHAction {

    private String accessToken;
    private String jsApiTicket;
    private Long getTiketTime = 0L;
    private Long getTokenTime = 0L;
    private Long tokenExpireTime = 0L;
    private Long ticketExpireTime = 0L;

    //接收微信公众号号消息
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = "/wx/gzh/notice/accept")
    @ResponseBody
    public void accept_wx_gzh_notice(HttpServletRequest request, HttpServletResponse response) {

        boolean isGet = request.getMethod().toLowerCase().equals("get");
        if (isGet) {
            PrintWriter print;
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 随机字符串
            String echostr = request.getParameter("echostr");

            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (signature != null && WXTokenCheckoutUtil.checkSignature(signature, timestamp, nonce)) {
                try {
                    print = response.getWriter();
                    print.write(echostr);
                    print.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {

            Map<String, String> map = null;
            try {
                map = MessageUtil.parseXml(request);
            } catch (Exception e) {
                e.printStackTrace();
            }

            System.out.println(map.get("MsgType"));
            String msgType = map.get("MsgType");
            if (ValidateUtil.isNotNull(msgType) && msgType.equalsIgnoreCase("event")) {
                System.out.println(map.get("MsgType") + "," + map.get("Event"));

                switch (map.get("Event")) {
                    case "subscribe": {//关注
                        String eventKey = map.get("EventKey");

                        System.out.println(eventKey);
                        System.out.println(eventKey.substring(0, 7));
                        if (ValidateUtil.isNotNull(eventKey) && eventKey.length() >= 8) {
                            if ("qrscene_".equalsIgnoreCase(eventKey.substring(0, 8))) {//二维码扫描关注
                                String fromu = eventKey.substring(8);
                                System.out.println("来自：" + fromu);
                                UserInfo fromUserInfo = UserInfoMemory.getInstance().getUserInfo(fromu);
                                if (null != fromUserInfo) {
                                    String dUserOpenId = fromUserInfo.getWxOpenId();
                                    if (ValidateUtil.isNull(dUserOpenId)) {
                                        //为空无法推送
                                    } else {
                                        //给上级推送通知
                                        String userOpenId = map.get("FromUserName");
                                        //该用户是否为本系统用户
                                        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfoByOpenId(userOpenId);
                                        if (null != userInfo) {
                                            //是的话直接获取信息推送通知
                                            pushNewUserMsg("9Nrt1fahRGlboK1QJ0SOXnwrXzGaViPUtFpoEmLOaWY", "新会员加入通知", dUserOpenId, userInfo.getId() + "", "新的朋友加入");
                                        } else {
                                            //创建本地系统账号
                                            ResultInfo resultInfo = UserLogin.loginByWxOpenId("", userOpenId, UserType.USER, IsBindAccount.NotBind);
                                            if (null != resultInfo && resultInfo.isSuccess()) {
                                                userInfo = UserInfoMemory.getInstance().getUserInfoByOpenId(userOpenId);
                                                if (null != userInfo) {
                                                    //是的话直接获取信息推送通知
                                                    pushNewUserMsg("9Nrt1fahRGlboK1QJ0SOXnwrXzGaViPUtFpoEmLOaWY", "新会员加入通知", dUserOpenId, userInfo.getId() + "", "新的朋友加入");
                                                }
                                            } else {
                                                System.out.println("用户扫码关注公众号，但是创建账号失败了");
                                            }
                                            //并向分享系统推送信息
                                            //形成上下级
                                            if (null != SYS_SETTINGS.IS_OPEN_DISTRIBUTION && 0 == 1 - SYS_SETTINGS.IS_OPEN_DISTRIBUTION) {
                                                //开启分销模式
                                                String requrstStr = HttpRequest.sendPost(SYS_CONFIG_PATH.FEN_XIAO_SERVICE_URL + "/api/distribute/user/relation/add"
                                                        , "username=" + userOpenId + "&topAgent=" + fromu + "&sysCustomer=" + SYS_CONFIG_PATH.FEN_XIAO_SERVICE_KEY);
                                                DeviceCompanyContact companyContact = new Gson().fromJson(requrstStr, DeviceCompanyContact.class);
                                                if (null == companyContact) {
                                                    System.out.println("分销处理失败[微信关注，形成上下级失败]");
                                                }
                                                if (0 == 1 - companyContact.getStatus()) {
                                                    System.out.println("分销处理-建立上下级失败");
                                                }
                                            }
                                        }
                                    }

                                }

                            }
                        } else {
                            //正常关注
                        }

                    }
                    break;
                    case "unsubscribe": {//取消关注
                        System.out.println("取消关注");
                    }
                    break;
                }
            }

        }

    }

    //获取公众号二维码
    @RequestMapping(method = RequestMethod.POST, value = "/wx/gzh/qrcode/get")
    @ResponseBody
    public String getAccessToken(String sysAppKey, String appFlag, String token, String username) {
//        UserInfo user = null;
//        if (ValidateUtil.isNotNull(token)) {
//            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
//        } else if (ValidateUtil.isNotNull(username)) {
//            user = UserInfoMemory.getInstance().getUserInfo(username);
//        }
        if (ValidateUtil.isNull(username)) {
            if (ValidateUtil.isNotNull(token)) {
                UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
                if (null == user) {
                    return AjaxResult.errorLogoutResult();
                }
                username = user.getUsername();
            } else {
                return AjaxResult.errorLogoutResult();
            }
        }
//        if (user == null) {
//            return AjaxResult.errorLogoutResult();
//        }

        // 第三方用户唯一凭证
//        String appId = "wxa1cf65e96c2ccb5b";
        // 第三方用户唯一凭证密钥
//        String appSecret = "5d29fd20937d38e5c384bf1086fb36a5";

        // 调用接口获取access_token

        String gzhAppId = WeixinConfig.gzhAppId;
        String gzhAppSecret = WeixinConfig.gzhAppSecret;
        if (ValidateUtil.isNotNull(appFlag)) {
            SysConfigPay sysConfigPay = SysConfigPayMemory.getInstance().getByKey(sysAppKey, appFlag);
            if (null != sysConfigPay) {
                gzhAppId = sysConfigPay.getWxXcxAppId();
                gzhAppSecret = sysConfigPay.getWxXcxAppSecret();
            }
        }
        if (ValidateUtil.isNull(gzhAppId) || ValidateUtil.isNull(gzhAppSecret)) {
            return AjaxResult.errorResult("公众号配置不正确");
        }
        AccessToken at = WeixinUtil.getAccessToken(gzhAppId, gzhAppSecret);
        String url = WeixinUtil.getGzhForeverQRCode(at.getToken(), username);

        return AjaxResult.successResult(url);
    }

    //获取小程序二维码
    @RequestMapping(method = RequestMethod.POST, value = "/wx/xcx/qrCode/get")
    @ResponseBody
    public String xcx_qr_code_get(String sysAppKey, String appFlag, String path, String params) {

        String xcxAppId = WeixinConfig.xcxAppId;
        String xcxAppSecret = WeixinConfig.xcxAppSecret;
        if (ValidateUtil.isNotNull(appFlag)) {
            SysConfigPay sysConfigPay = SysConfigPayMemory.getInstance().getByKey(sysAppKey, appFlag);
            if (null != sysConfigPay) {
                xcxAppId = sysConfigPay.getWxXcxAppId();
                xcxAppSecret = sysConfigPay.getWxXcxAppSecret();
            }
        }
        if (ValidateUtil.isNull(xcxAppId) || ValidateUtil.isNull(xcxAppSecret)) {
            return AjaxResult.errorResult("小程序appid配置不正确");
        }
        AccessToken at = WeixinUtil.getAccessToken(xcxAppId, xcxAppSecret);
//        String url =  WeixinUtil.getXcxQrCode(at.getToken(), "pages/shareRegist/shareRegist", "15666371607");
        JYAssertUtils.isNull(at, "未获取到配置信息");
        if (ValidateUtil.isNull(path)) {
            path = "pages/shareReg/shareReg";
        }
        String url = WeixinUtil.getXcxQrCode(at.getToken(), path, params);
        return AjaxResult.successResult(url);
    }

    //获取用户公众号信息
    @RequestMapping(method = RequestMethod.POST, value = "/wx/gzh/userinfo/get")
    @ResponseBody
    public String getGzhUserInfo(String token, String username) {
        UserInfo userInfo = null;
        if (ValidateUtil.isNull(username) && ValidateUtil.isNotNull(token)) {
            return AjaxResult.errorLogoutResult();
        } else if (ValidateUtil.isNull(username)) {
            if (ValidateUtil.isNotNull(token)) {
                userInfo = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
                if (null == userInfo) {
                    return AjaxResult.errorLogoutResult();
                }
                username = userInfo.getUsername();
            }
        } else {
            userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        }

        if (null == userInfo) {
            return AjaxResult.errorResult("该用户不存在");
        }

        if (ValidateUtil.isNull(userInfo.getWxOpenId())) {
            return AjaxResult.errorResult("未获取到用户的openId");
        }

        if (ValidateUtil.isNull(WeixinConfig.gzhAppId) || ValidateUtil.isNull(WeixinConfig.gzhAppSecret)) {
            return AjaxResult.errorResult("公众号配置不正确");
        }
        AccessToken at = WeixinUtil.getAccessToken(WeixinConfig.gzhAppId, WeixinConfig.gzhAppSecret);
        String info = WeixinUtil.getGzhUserInfo(at.getToken(), userInfo.getWxOpenId());

        return AjaxResult.successResult(info);
    }

    //创建菜单
    @RequestMapping(method = RequestMethod.POST, value = "/wx/gzh/menu/create")
    @ResponseBody
    public String createMenu(String data) {
        if (ValidateUtil.isNull(data)) {
            return AjaxResult.errorResult("data不能为空");
        }
        // 断言代替 JYAssertUtils.isNull(data, "data不能为空");
        AccessToken at = WeixinUtil.getAccessToken(WeixinConfig.gzhAppId, WeixinConfig.gzhAppSecret);
        String info = WeixinUtil.createGzhMenu(at.getToken(), data);

        return AjaxResult.successResult(info);
    }

    //删除菜单
    @RequestMapping(method = RequestMethod.POST, value = "/wx/gzh/menu/del")
    @ResponseBody
    public String delMenu() {

        AccessToken at = WeixinUtil.getAccessToken(WeixinConfig.gzhAppId, WeixinConfig.gzhAppSecret);
        String info = WeixinUtil.deleteGzhMenu(at.getToken());

        return AjaxResult.successResult(info);
    }


    //获取微信参数
    @RequestMapping(method = RequestMethod.POST, value = "/wechatParam")
    @ResponseBody
    public String getWechatParam(String url) {
        //当前时间
        long now = System.currentTimeMillis();
//        System.out.println("currentTime====>" + now + "ms");

        //判断accessToken是否已经存在或者token是否过期
        if (StringUtils.isBlank(accessToken) || (now - getTokenTime > tokenExpireTime * 1000)) {
            AccessToken at = WeixinUtil.getAccessToken(WeixinConfig.gzhAppId, WeixinConfig.gzhAppSecret);
            if (at != null) {
                accessToken = at.getToken();
                tokenExpireTime = (long) at.getExpiresIn();
                //获取token的时间
                getTokenTime = System.currentTimeMillis();
//                System.out.println("accessToken====>" + accessToken);
//                System.out.println("tokenExpireTime====>" + tokenExpireTime + "s");
//                System.out.println("getTokenTime====>" + getTokenTime + "ms");
            }
        } else {
//            System.out.println("====>tokenInfo is null~");
//            System.out.println("====>failure of getting tokenInfo,please do some check~");
        }


        //判断jsApiTicket是否已经存在或者是否过期
        if (StringUtils.isBlank(jsApiTicket) || (now - getTiketTime > ticketExpireTime * 1000)) {
            JSONObject ticketInfo = WeixinUtil.getJsApiTicket(accessToken);
            if (ticketInfo != null) {
//                System.out.println("ticketInfo====>" + ticketInfo.toJSONString());
                jsApiTicket = ticketInfo.getString("ticket");
                ticketExpireTime = ticketInfo.getLong("expires_in");
                getTiketTime = System.currentTimeMillis();

//                System.out.println("jsApiTicket====>" + jsApiTicket);
//                System.out.println("ticketExpireTime====>" + ticketExpireTime + "s");
//                System.out.println("getTiketTime====>" + getTiketTime + "ms");
            }
        } else {
//            System.out.println("====>ticketInfo is null~");
//            System.out.println("====>failure of getting tokenInfo,please do some check~");
        }
        //生成微信权限验证的参数
        Map<String, String> wechatParam = makeWXTicket(jsApiTicket, url);
        return AjaxResult.successResult(wechatParam);


//        Map info = new HashMap();
//        info.put("userNum", userNum);
//        info.put("orderNum", orderNum);
//        JSONObject obj = new JSONObject();
//        obj.put("status", 1);
//        obj.put("totalCount", count);
//        obj.put("data", JSONArray.toJSON(list == null ? Collections.emptyList() : list));
//        obj.put("info", JSONObject.toJSON(info));
//        return obj.toString();
    }


    //生成微信权限验证的参数
    public Map<String, String> makeWXTicket(String jsApiTicket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonceStr = createNonceStr();
        String timestamp = createTimestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsApiTicket +
                "&noncestr=" + nonceStr +
                "&timestamp=" + timestamp +
                "&url=" + url;
//        System.out.println("String1=====>" + string1);
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
//            System.out.println("signature=====>" + signature);
        } catch (NoSuchAlgorithmException e) {
//            log.error("WeChatController.makeWXTicket=====Start");
//            log.error(e.getMessage(), e);
            System.out.println(e.getMessage());
//            log.error("WeChatController.makeWXTicket=====End");
        } catch (UnsupportedEncodingException e) {
            System.out.println(e.getMessage());
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsApiTicket);
        ret.put("nonceStr", nonceStr);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        ret.put("appid", WeixinConfig.gzhAppId);
        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    //生成随机字符串
    private static String createNonceStr() {
        return UUID.randomUUID().toString();
    }

    //生成时间戳
    private static String createTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }


    public static void main(String[] args) {

//        pushNewOrderMsg("T4n3tj1I65uqw2CUVkqh-OIslBbUu6GB7WEkXIJWHSo", "",
//                "o-lL25YG-CET2c6_tYoM1-E6qh6E", "3709231996", "水果捞店铺", "13645457878", "15553135560");

//        pushNewUserMsg();
//        pushNewOrderMsg();


        // 第三方用户唯一凭证
//        String appId = "wx4fd6dc26b7cc3da1";
//        // 第三方用户唯一凭证密钥
//        String appSecret = "e7491638728bd4b084bfa27fd27f1115";
//
//        // 调用接口获取access_token
//        AccessToken at = WeixinUtil.getAccessToken(appId, appSecret);
//        String url = WeixinUtil.getGzhForeverQRCode(at.getToken(), "");
//        System.out.println(url);


//        boolean flag = pushNewUserMsg("9Nrt1fahRGlboK1QJ0SOXnwrXzGaViPUtFpoEmLOaWY", "新会员加入通知", "o3CkM01T3xPGPPjhd72RZ_WaWl_U", "111", "新会员加入");
//        System.out.println(flag + "");


//        System.out.println(pushNewOrderMsg(null));


//        pushNewOrderMsg("wx291412009921933509cfd92c1593209000");

//        WxGzhActionMan.sendGzhMsg(userInfo.getWxGzhOpenId(),
//                sysSetting.getNote(),
//                title, "",
//                title, content);
    }


    public static boolean pushNewUserMsg(String templateId, String title, String toUserWxOpenId, String userId, String note) {
        // 第三方用户唯一凭证
//        String appId = "wx4fd6dc26b7cc3da1";
//        String appId = "wx0a3fc42a0de29fa2";//boss数据通
        // 第三方用户唯一凭证密钥
//        String appSecret = "e7491638728bd4b084bfa27fd27f1115";
//        String appSecret = "7c72514c9aab0e8d701189b8698a5d22";//boss数据通
        HashMap dataMap = new HashMap();
        dataMap.put("first", new WXMsgTemplate(title));
        dataMap.put("keyword1", new WXMsgTemplate(userId));
        dataMap.put("keyword2", new WXMsgTemplate(DateUtils.getCurrentDateTime()));
        dataMap.put("remark", new WXMsgTemplate(note));
//        String toUser = "oH_sH1GhIPnMHlvwDjr6eld80YtY";
//        String template_id = "TB-JdD3QNHAnrgvDTQ3JUs8TjhDHJFoDf5JAn3Ft8H8";
//        String url = "http://weixin.qq.com";
//        String topcolor = "#FF0000";
        String url = null;
        String topcolor = null;

        //需要跳转的小程序
        HashMap<String, String> xcxMap = new HashMap<>();
        xcxMap.put("appid", WeixinConfig.gzhAppId);
        xcxMap.put("pagepath", "/pages/index/index");


        return WXXcxMan.pushXcxhMsg(WeixinConfig.gzhAppId, WeixinConfig.gzhAppSecret,
                toUserWxOpenId, templateId,
                url, topcolor,
                xcxMap,
                dataMap);
    }


    // 服务通知
    public static boolean pushNewOrderMsg(String sysAppKey, String appFlag, String templateId, String formId, String toUserWxOpenId, String orderNo,
                                          String shopName, String shopPhone, String riderPhone) {

        HashMap dataMap = new HashMap();

        // 从缓存获取推送配置
        List<SysConfigXcxPush> list = SysConfigXcxPushMemory.getInstance().list("0");
        if (ValidateUtil.isAbsList(list) && list.get(0) != null) {
            SysConfigXcxPush sysConfigXcxPush = list.get(0);

            dataMap.put(sysConfigXcxPush.getOrderNo(), new WXMsgTemplate(orderNo)); // 订单编号
            dataMap.put(sysConfigXcxPush.getTime(), new WXMsgTemplate(DateUtils.sdfDateTime.get().format(new Date())));  //  //DateUtils.getCurrentDateTime() 订单编号

            dataMap.put(sysConfigXcxPush.getShopName(), new WXMsgTemplate(shopName));  //  // 门店名称
            dataMap.put(sysConfigXcxPush.getShopPhone(), new WXMsgTemplate(shopPhone));  //  // 联系方式
            dataMap.put(sysConfigXcxPush.getRiderPhone(), new WXMsgTemplate(riderPhone));  //配送员电话
        } else {
            dataMap.put("character_string1", new WXMsgTemplate(orderNo)); // 订单编号
            dataMap.put("date3", new WXMsgTemplate(DateUtils.sdfDateTime.get().format(new Date())));  //  //DateUtils.getCurrentDateTime() 订单编号

            dataMap.put("thing2", new WXMsgTemplate(shopName));  //  // 门店名称
            dataMap.put("phone_number5", new WXMsgTemplate(shopPhone));  //  // 联系方式
            dataMap.put("phone_number10", new WXMsgTemplate(riderPhone));  //配送员电话
        }

//        String toUserWxOpenId = "onOeO4gZtgfzkYAb00GMaFYSfIR0";
//        String templateId = "JhAxZdF7CPrB2grKceXS2MvlRJYZXWaA_0RvM3OvOwI";
//        String url = "http://weixin.qq.com";
//        String topcolor = "#FF0000";
        String url = null;
        String topcolor = null;
//        WeixinConfig.xcxAppId = "wxb913a56e540bb084";
//        WeixinConfig.xcxAppSecret = "d38242ccef6e4ee061eac37f79c9b2fa";


        String xcxAppId = WeixinConfig.xcxAppId;
        String xcxAppSecret = WeixinConfig.xcxAppSecret;
        if (ValidateUtil.isNotNull(appFlag)) {
            SysConfigPay sysConfigPay = SysConfigPayMemory.getInstance().getByKey(sysAppKey, appFlag);
            if (null != sysConfigPay) {
                xcxAppId = sysConfigPay.getWxXcxAppId();
                xcxAppSecret = sysConfigPay.getWxXcxAppSecret();
            }
        }
        //需要跳转的小程序
        HashMap<String, String> xcxMap = null;
        if (ValidateUtil.isNotNull(xcxAppId)) {
            xcxMap = new HashMap<>();
            xcxMap.put("appid", xcxAppId);
            xcxMap.put("pagepath", "/pages/index-new/index-new");
        }

        return WXXcxMan.pushXcxhMsg(xcxAppId, xcxAppSecret,
                toUserWxOpenId, templateId,
                url, topcolor,
                xcxMap,
                dataMap,
                formId);
    }


    //小程序发布模板消息
    @RequestMapping(method = RequestMethod.POST, value = "/wx/xcx/message/send")
    @ResponseBody
    public String xcx_message(String sysAppKey, String appFlag, String formId, String parentUsername, String username) {
        if (ValidateUtil.isNull(username)) {
            System.out.println("未传用户账号，小程序模板消息未发布");
            return AjaxResult.errorResult("用户账号为空");
        }
        System.out.println(formId + "," + parentUsername + ":" + username);


        if (ValidateUtil.isNotNull(parentUsername)) {
            //推送给上级短信
//            SMSInfo smsInfo = new SMSInfo(parentUsername, null,
//                    null, DUBBO_SMS_TYPE.OTHER,
//                    SYS_CONFIG_SMS.FENXIAO_PARENT_NOTICE);
//            SMSThreadMap.smsCodeSet.add(smsInfo);

            JYSmsSeverBusiness.sendSMS(sysAppKey, parentUsername, SMS_TYPE.FENXIAO_PARENT_NOTICE);

            //本地添加一个用户
            try {
                User.addUser(username, "123456", UserType.SHOP_OWNER);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //开启分销模式
            String requrstStr = HttpRequest.sendPost(SYS_CONFIG_PATH.FEN_XIAO_SERVICE_URL + "/api/distribute/user/relation/add"
                    , "username=" + username + "&topAgent=" + parentUsername + "&sysCustomer=" + SYS_CONFIG_PATH.FEN_XIAO_SERVICE_KEY);
            DeviceCompanyContact companyContact = new Gson().fromJson(requrstStr, DeviceCompanyContact.class);
            if (null == companyContact) {
                System.out.println("分销处理失败[微信关注，形成上下级失败]");
            }
            if (0 == 1 - companyContact.getStatus()) {
                System.out.println("分销处理-建立上下级失败");
            }

            //推送给上级模板消息
            UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(parentUsername);
            if (null == userInfo) {
                System.out.println("小程序-模板消息：上级不存在");
            } else {
                String xcxOpenId = userInfo.getWxXcxOpenId();
                System.out.println(parentUsername + "->:" + xcxOpenId);
                if (ValidateUtil.isNull(xcxOpenId)) {
                    System.out.println("小程序-模板消息：上级小程序openId不存在");
                } else {
                    pushXcxNewUserMsg(sysAppKey, appFlag, "bm71cUo0U5dF8Kp6r3-2OGkC8EPnJTizrrLSqlwz_DQ", "新会员加入通知", xcxOpenId, "新的朋友加入", formId);
                }
            }
        } else {
            System.out.println("小程序-模板消息：上级账号为空");
        }


        UserInfoVO userInfoVO = UserLogin.loginNotCheck(username);

        return AjaxResult.successResult(userInfoVO);
    }


    public static boolean pushXcxNewUserMsg(String sysAppKey, String appFlag, String templateId, String title, String toUserWxOpenId, String note, String formId) {
        HashMap dataMap = new HashMap();
        dataMap.put("keyword1", new WXMsgTemplate(DateUtils.getCurrentDateTime()));//注册时间
        dataMap.put("keyword2", new WXMsgTemplate(title));//温馨提示
        dataMap.put("keyword3", new WXMsgTemplate(note));//备注


        String url = null;
        String topcolor = null;


        String xcxAppId = WeixinConfig.xcxAppId;
        String xcxAppSecret = WeixinConfig.xcxAppSecret;
        if (ValidateUtil.isNotNull(appFlag)) {
            SysConfigPay sysConfigPay = SysConfigPayMemory.getInstance().getByKey(sysAppKey, appFlag);
            if (null != sysConfigPay) {
                xcxAppId = sysConfigPay.getWxXcxAppId();
                xcxAppSecret = sysConfigPay.getWxXcxAppSecret();
            }
        }

        //需要跳转的小程序
        HashMap<String, String> xcxMap = new HashMap<>();
        xcxMap.put("appid", xcxAppId);
        xcxMap.put("page", "pages/index/index");

        return WXXcxMan.pushXcxhMsg(xcxAppId, xcxAppSecret,
                toUserWxOpenId, templateId,
                url, topcolor,
                xcxMap,
                dataMap,
                formId);
    }


}
